package org.csu.storemanage.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Param;
import org.csu.storemanage.pojo.User;
import org.csu.storemanage.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import org.csu.storemanage.pojo.SendSms;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;
import java.util.Objects;


@Controller
public class UserController
{
    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private UserService userService;

    @Autowired
    UserController(UserService userService)
    {
        this.userService = userService;
    }

    @GetMapping("/signIn")
    String getSignIn(HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        if (session.getAttribute("username") == null)
            return "login";
        else
            return "redirect:/index";
    }

    @PostMapping("/signIn")
    @ResponseBody
    String postSignIn(HttpServletRequest request)
    {
        String method = request.getParameter("method");
        User user;

        if (method.equals("username"))//账号密码登录
        {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            user = userService.findUserByUsername(username);
            if (user == null)
            {
                return "invalid username";
            } else if (Objects.equals(UserService.md5(password), user.getPassword()))
            {
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                session.setAttribute("userID", user.getUser_id());
                session.setAttribute("admin",user.isAdmin());
                return "success";
            } else
            {
                return "wrong password";
            }
        } else if (method.equals("phone"))//手机号登录
        {
            String phone;
            String code;
            phone = request.getParameter("phoneNumber");
            code = request.getParameter("validateCode");
            user = userService.findUserByPhone(phone);
            if (user == null)
            {
                return "invalid phone";
            }
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            System.out.println(jedis.get("yzm"));
            System.out.println(code);
            if (Objects.equals(code, jedis.get("yzm")) && user.getPhone().equals(phone))
            {
                HttpSession session = request.getSession();
                session.setAttribute("username", user.getUsername());
                session.setAttribute("userID", user.getUser_id());
                session.setAttribute("admin",user.isAdmin());
                return "success";
            } else if (jedis.exists("yzm") && ! Objects.equals(code, jedis.get("yzm")))
            {
                return "invalid code";
            } else if (! jedis.exists("yzm"))
            {
                return "over time";
            } else
            {
                return "wrong";
            }
        } else
        {
            return "wrong";
        }
    }

    @GetMapping("/signUp")
    String getSignUP(HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        if (session.getAttribute("username") == null)
            return "signup";
        else
            return "redirect:/index";
    }

    @PostMapping("/sms/sendCodeAgain")
    @ResponseBody
    public String sendCodeAgain(@RequestParam(value = "phone", required = true) String phone)
    {
//        if(userService.findUserByPhone(phone)==null)
//            return "invalid phone";
        String[] phones = {"+86" + phone};
        SendStatus[] ret = SendSms.sendSms(phones);
        return "ok";
    }

    @GetMapping("/code")
    @ResponseBody
    String checkCode(HttpServletRequest request)
    {
        String code;
        code = request.getParameter("validateCode");
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        System.out.println(Objects.equals(code, jedis.get("yzm")));
        if (Objects.equals(code, jedis.get("yzm")))
        {
            return "success";
        } else if (! Objects.equals(code, jedis.get("yzm")))
        {
            return "invalid code";
        } else
        {
            return "wrong";
        }
    }

    @PostMapping("/signUp")
    String postSignUp(HttpServletRequest request)
    {
        try
        {
            String code;
            code = request.getParameter("validateCode");
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            System.out.println(Objects.equals(code, jedis.get("yzm")));
            if (Objects.equals(code, jedis.get("yzm")))
            {
                User user = new User(request.getParameter("username"), request.getParameter("password"), request.getParameter("phoneNumber"));
                int userId = userService.insertUser(user);
                HttpSession session = request.getSession();
                session.setAttribute("username", request.getAttribute("username"));
                session.setAttribute("userId", userId);
                session.setAttribute("admin",false);
                return "redirect:/index";
            } else if (! Objects.equals(code, jedis.get("yzm")))
            {
                request.getSession().setAttribute("errMsg", "invalid code");
                return "signup";
            } else
            {
                request.getSession().setAttribute("errMsg", "发生了不明错误，请重试。");
                return "signup";
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            request.getSession().setAttribute("errMsg", "发生了不明错误，请稍后再试。");
            return "signup";
        }
    }

    @GetMapping("/logout")
    @ResponseBody
    String logout(HttpServletRequest request)
    {
        try
        {
            request.getSession().invalidate();
        }
        catch (Exception e)
        {
            return "fail";
        }
        System.out.println("success");
        return "success";
    }

    @GetMapping("/usernameExit")
    @ResponseBody
    String checkUsername(@Param("username") String username)
    {
        if (userService.isUsernameExist(username))
            return "yes";
        else
            return "no";
    }

    @GetMapping("/phoneExit")
    @ResponseBody
    String checkPhone(@Param("phone") String phone)
    {
        if (userService.isPhoneExist(phone))
            return "yes";
        else
            return "no";
    }

    @GetMapping("/userManage")
    String userManager(HttpServletRequest request, HttpServletResponse response)
    {
        //验证是否为管理员
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null)
        {
            session.setAttribute("errMsg", "用户未登录");
            return "login";
        } else
        {
            if (!userService.findUserByUsername(username).isAdmin())
            {
                session.setAttribute("errMsg", "没有管理员权限");
                return "redirect:/index";
            }
        }
        //验证通过
        List<User> userList = userService.findAllUser();
        request.getSession().setAttribute("userList", userList);
        return "userManager";
    }

    @PutMapping("/userManage")
    @ResponseBody
    String userManage(HttpServletRequest request)
    {

        String type = request.getParameter("type");
        String username = request.getParameter("manageUsername");
        if (type.equals("resetPassword"))
        {
            try
            {
                return userService.resetUserPassword(username);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return "error";
            }
        } else if (type.equals("changePassword"))
        {
            try
            {
                String newPassword = request.getParameter("newPwd");
                return userService.changeUserPasswordByUsername(username, newPassword);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return "error";
            }
        } else if (type.equals("deleteUser"))
        {
            try
            {
                userService.deleteUserByUsername(username);
                return "success";
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return "error";
            }

        } else
        {
            return "error";
        }

    }
}
